import { Plugin } from 'vite'
import fs from 'node:fs'
import path from 'node:path'
import * as electronBuilder from 'electron-builder'

async function buildEsbuildBackground() {
  // build background.js
  require('esbuild').buildSync({
    entryPoints: ['electron/background.ts'],
    outfile: 'dist/background.js',
    platform: 'node',
    target: 'node22',
    bundle: true,
    external: ['electron'],
  })
}
export const ElectronBuildPlugins = (): Plugin => {
  return {
    name: 'electron-build',
    closeBundle() {
      buildEsbuildBackground()
      // electron packager main.js
      const json = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
      json.main = 'background.js'

      fs.writeFileSync('dist/package.json', JSON.stringify(json, null, 2))

      fs.mkdirSync('dist/node_modules')

      // electron build

      electronBuilder.build({
        config: {
          appId: 'com.electron.app',
          productName: 'electron-app',
          directories: {
            output: path.resolve(process.cwd(), 'release'),
            app: path.resolve(process.cwd(), 'dist'),
          },
          asar: true, // asar打包
          nsis: {
            oneClick: false, // 一键安装
            allowToChangeInstallationDirectory: true, // 允许修改安装目录
          },
          mac: {
            target: ['dmg'],
          },
          win: {
            target: ['nsis'],
          },
          linux: {
            target: ['AppImage'],
          },
        },
      })
    },
  }
}
